//
//  TicketContentVM.swift
//  ANOA
//
//  Created by 邱仙凯 on 2019/6/16.
//  Copyright © 2019 zwb. All rights reserved.
//

import UIKit




struct TContentStruct {
    var openFlag:Bool
    var tkModel:TicketModel {
        didSet {
            if tkModel.fInvoicetypeNm != oldValue.fInvoicetypeNm || self.performArray.count < 1 {
                let reimType_one = prepare4reimType(tkModel.fInvoicetypeNm.unwrap)
                self.reimTypeArray = reimType_one
            
                if !reimType_one.contains(tkModel.fBxtypeNm) {
                    tkModel.fBxtypeNm = reimType_one.first!
                    
                    for (key,value ) in reimbType {
                        if value == tkModel.fBxtypeNm {
                            tkModel.fBxtypeId = Int(key)!
                        }
                    }
                }
                self.performArray = InvoiceType.typeForArray(tkModel.fInvoicetypeId.unwrap, fcompany: tkModel.fCompany.intWrap,checkState: tkModel.fCheckstate.unwrap)
            }
              
            
        }
    }
    
    var performArray:[String]
    var reimTypeArray:[String]
    var picMainArr:[PictureModel]
    var picArr2:[PictureModel]
    var files:[FileAssistModel]?
 
    
}

 


class TicketContentVM: NSObject {
    
    var vc:TicketContentController?
    var invoiceTypeCode = "" // 1 为销售发票  其他为其他
    
    func ticketModel2Json(_ one:TicketModel) -> String {
        var one_s = one
        if one_s.details == nil {
            let arr = [TicketDetailModel]()
            one_s.details = arr
        }
        let maindic = one_s.dictionaryRepresentation()
        let mainjson = dictionaryToJson(maindic)
        return mainjson
    }
    
    func picModel2Json(picMainArr:[PictureModel],picArr2:[PictureModel]) -> String {
        var picStr:String = ""
        var allPic = picMainArr + picArr2
        for i in 0..<allPic.count {
            if let realimg = allPic[i].img {
                allPic[i].fPicByte =  realimg.toBase64()
                let str = dictionaryToJson(allPic[i].dictionaryRepresentation())
                if i == allPic.count - 1 {
                    picStr = picStr + str
                } else {
                    picStr = picStr + str + ","
                }
            }
        }
        let picjsonArr = "[" + picStr + "]"
        return picjsonArr
    }
    func fileModel2Json(files:[FileAssistModel]?) -> String {
        if let ffff = files {
            let xxx = ffff.filter { $0.idKey.unwrap != "" }
            if  xxx.count > 0 {
                let jsonArr = xxx.compactMap {  dictionaryToJson($0.dictionaryRepresentation() ) }
                let jsonStr = jsonArr.joined(separator: ",")
                let jsonEnd = "[\(jsonStr)]"
                   return jsonEnd
            } else {
                return "[]"
            }
            
        } else {
            return "[]"
        }
        
    }
    // 多张保存
    func saveMutiContinue(_ array:[TContentStruct])  {
        
        var jsonStr:String = ""
        for i in 0..<array.count {
            
            let picjson = picModel2Json(picMainArr: array[i].picMainArr, picArr2: array[i].picArr2)
            let modeljson = ticketModel2Json(array[i].tkModel)
            
            let onejson = "{\"data\":\(modeljson),\"str_pics\":\(picjson)}"
            
            if i == array.count - 1 {
                jsonStr = jsonStr + onejson
            } else {
                jsonStr = jsonStr + onejson + ","
            }
        }
        let endjsonArr = "[" + jsonStr + "]"
        
        let filedatas = array.compactMap { $0.files }.flatMap { $0 }
        
        // 执行保存多张的操作
        KSNetwork.shared.loadAny(API.invoice(.insertAllInvoice(invoiceTypeCode: "\(self.invoiceTypeCode)", invoiceList: endjsonArr, files: filedatas)),showHud: true, successHandle: {  (json) in
         
            guard let result = json as? [String: Any] else {
                return
            }
            // 判断啥白名单用的，服务端使用
            let forgid = self.vc!.dataArray.first?.tkModel.fOrgId
            let msg = result["message"] as? String
            let flag = result["flag"] as? String
            if flag == TRUE {
//
                let json = JSON(result["infos"] as Any).arrayValue
                let items = json.map { TicketModel(json: $0) }
                let needCheckArr = items.filter { ifNeedCheck(one:$0) }
//
                if needCheckArr.count > 0 { // 有需要查验的发票
//
                    alertUtil(self.vc!, title: "保存成功，是否立即校验", withCancel: false,operateS: [nameAction(name: "立即校验", action: { (_) in
                        
                        var api:API!
                        if TicketAppear.shared.checkType == .typev4 {
                            api = API.invoice(.checkInvoiceMulitiV4(checkInvoices: models2json(needCheckArr),invoiceTypeCode: self.invoiceTypeCode,f_org_id: forgid.unwrap))
                        } else {
                            api = API.invoice(.checkInvoiceMulitiV1(checkInvoices: models2json(needCheckArr),invoiceTypeCode: self.invoiceTypeCode,f_org_id: forgid.unwrap))
                        }

                        KSNetwork.shared.doRequest4Sj(api) { (data:SwResult<notT>) in
                            KSToast("已发起查验,请耐心等待结果",duration: 2)
                            if let block = self.vc!.refreshBlock {
                                block()
                            }
                            self.vc!.navigationController?.popViewController(animated: true)
                        }

                    }),nameAction(name: "暂不校验", action: { (_) in
                        if let block = self.vc!.refreshBlock {
                            block()
                        }
                        self.vc!.navigationController?.popViewController(animated: true)
                    })])

                } else {
                    KSToast("保存成功")
                    if let block = self.vc!.refreshBlock {
                        block()
                    }
                    self.vc!.navigationController?.popViewController(animated: true)
                }
//
//
            } else {
                // 把出错信息展示在列表上
                let json = JSON(result["infos"] as Any).arrayValue
                let items = json.map { FpErrorModel(json: $0) }
                for i in 0..<self.vc!.dataArray.count {
                    self.vc!.dataArray[i].openFlag = false // 折叠起来好看点
                    self.vc!.dataArray[i].tkModel.errorMsg = "" // 先清空错误信息，防止旧的错误信息已修复却还提示
                    items.forEach {
                        if  "\(i)" == $0.fp_number {
                            self.vc!.dataArray[i].tkModel.errorMsg = $0.message
                        }
                    }
                }
                self.vc!.tableView.reloadData()
            }
            
            
             
            
        }, errorHandle: {
            print("出错了")
        })
 
    }

    
    // 单张保存
    func ticketSaveContinue(tkType:TkPhotoType, one:TicketModel,picMainArr:[PictureModel],picArr2:[PictureModel],files:[FileAssistModel]?,cTitle:String)  {
 
        var onexxx = one
        onexxx.fpNumber = "0"
        var api:API?
        if cTitle.contains("修改") {
            api = API.invoice(.modifyInvoice(tkType:tkType,invoiceTypeCode: "\(self.invoiceTypeCode)",data: ticketModel2Json(onexxx),str_pics: picModel2Json(picMainArr: picMainArr, picArr2: picArr2), fileArr: fileModel2Json(files: files),main: picMainArr, files: files))
        } else {
            api = API.invoice(.saveInvoice(tkType:tkType,invoiceTypeCode: "\(self.invoiceTypeCode)",data: ticketModel2Json(onexxx),str_pics: picModel2Json(picMainArr: picMainArr, picArr2: picArr2), fileArr: "[]",main: picMainArr, files: files))
        }
        
         KSNetwork.shared.doRequest(api!) { (result:BaseResult<TRepeatResult>) in
             if result.flag == TRUE {
                 onexxx.idKey = result.id_key
                  if one.fCheckstate != "1" && ifNeedCheck(one: one) {
                      
                       continueCheckAc()
                      
                      func continueCheckAc() {
                          alertUtil(title: "是否立即查验发票？", withCancel: false,operateS: [nameAction(name: "确定", action: { _ in
                              
                              var api:API!
                              if TicketAppear.shared.checkType == .typev4 {
                                  api = API.invoice(.checkInvoiceV4(qrcode: jointURLString(one),f_type: "2",id_key: onexxx.idKey.unwrap,invoiceTypeCode: self.invoiceTypeCode,f_buyername:one.fBuyername.unwrap,f_org_id:one.fOrgId.unwrap))
                              } else {
                                  api = API.invoice(.checkInvoiceV1(qrcode: jointURLString(one),f_type: "2",id_key: onexxx.idKey.unwrap,invoiceTypeCode: self.invoiceTypeCode,f_buyername:one.fBuyername.unwrap,f_org_id:one.fOrgId.unwrap))
                              }
                              
                              KSNetwork.shared.doRequest(api,showHud: false) { (data:BaseResult<OperateResult>) in
                                  
                              }
                              
                              alertUtil(title: "已提交查验，请后续刷新查看查验结果", withCancel: false,operateS: [nameAction(name: "确定", action: { _ in
                                   self.backAction()
                               })])
                         
                              
                          }),nameAction(name: "暂不", action: { _ in
                              self.backAction()
                          })])
                      }
                      

                 } else {
                     self.backAction()
                 }
                 
                 
                  
               
            } else {
                
                if result.message.unwrap.contains("发票重复") {
                    if let info = result.infoObjCombine {
                        self.vc!.repeatV.contentStr = "录入人员：\(info.f_owner_nm.unwrap)\n所属公司：\(info.f_org_nm.unwrap)\n所属部门：\(info.f_dept_nm.unwrap)"
                        
                        
                        if let kwindow =  getKeyWindow() {
                            kwindow.rootViewController!.view!.addSubview(self.vc!.repeatV)
                        }
                        
                        
                    }
                  } else {
                    KSToast(result.message)
                }
              }
            
            
            
        }
    
    }
    func backAction() {
        if let block = self.vc!.refreshBlock {
            block()
        }
        self.vc!.navigationController?.popViewController(animated: true)
    }
    
}
// 输入和选择判断 true 选择型  输入型
func selectTypeJudge(_ one_e:TicketModel,rowName:String) -> Bool {
    if rowName == "发票类型" || rowName == "报销类型"
        || rowName == "公司名称" || rowName == "发票日期" {
        return true
    } else {
        return false
    }
     
}

// 是否可编辑的判断
func editableJudge(_ one_e:TicketModel,rowName:String) -> Bool {
    if rowName == "报销状态" || rowName == "查验状态" {
        return false
    } else if  one_e.fCheckstate == "1" && one_e.fUseState == "未报销" {
        let nms = ["发票类型","发票日期","价税合计","发票金额","税额","金额(不含税)","发票代码","发票号码","校验码末6位","数电票号码末6位","购买方","购买方税号","服务名称","销售方","销售方税号","MainImg"]
        return !nms.contains(rowName)
    } else if one_e.fUseState == "已报销" {
        let nms = ["发票类型","报销类型","发票日期","价税合计","发票金额","税额","金额(不含税)","发票代码","发票号码","校验码末6位","数电票号码末6位","购买方","购买方税号","服务名称","销售方","销售方税号","MainImg"]
        return !nms.contains(rowName)
    } else {
        return true
    }
     
}
// 是否必填的判断
func mustJudge(_ one_e:TicketModel,rowName:String) -> Bool {
    if rowName == "发票号码" {
        if
            one_e.fInvoicetypeId.unwrap ==  InvoiceType.zzs_specific_01 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.carSaled_03 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_normal_04 ||
           
                one_e.fInvoicetypeId.unwrap == InvoiceType.jidaTax_12 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_specific_dianzi_08 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_normal_dianzi_10 ||
                
               
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_juan_11 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.quandianZ_21 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.quandianP_22 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.shudianZ_23 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.shudianP_24 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.trainTicket_SD_51 ||

                one_e.fInvoicetypeId.unwrap == InvoiceType.airtransportTicket_SD_61 ||

                one_e.fInvoicetypeId.unwrap == InvoiceType.CZB_80 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.SZ_QKL_81 ||
                    one_e.fInvoicetypeId.unwrap == InvoiceType.taxiTax_91 ||
                    one_e.fInvoicetypeId.unwrap == InvoiceType.qichepiao_93 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.dingTax_95 {
            return true
        } else {
           return false
        }
    }
    if rowName == "发票代码" {
        if  one_e.fInvoicetypeId.unwrap == InvoiceType.taxiTax_91 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.qichepiao_93 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.dingTax_95 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.jidaTax_12 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_normal_dianzi_10 ||
                one_e.fInvoicetypeId.unwrap ==  InvoiceType.zzs_specific_01 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.carSaled_03 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_normal_04 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.shudianZ_23 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.shudianP_24 ||

                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_juan_11 ||
               
                 one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_specific_dianzi_08 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.SZ_QKL_81 {
            return true
         } else {
            return false
        }
    }
    if rowName == "服务名称" {
             return false
     
    }
    if rowName == "金额(不含税)" {
        if  one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_specific_01 ||
                one_e.fInvoicetypeId.unwrap ==  InvoiceType.carSaled_03 ||
                one_e.fInvoicetypeId.unwrap ==  InvoiceType.zzs_normal_04 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_specific_dianzi_08 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_normal_dianzi_10 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_juan_11 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.quandianZ_21 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.quandianP_22 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.shudianZ_23 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.shudianP_24 ||

                one_e.fInvoicetypeId.unwrap == InvoiceType.airtransportTicket_SD_61 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.SZ_QKL_81  {
            return true
         } else {
            return false
        }
    }
    
    if rowName == "出发城市" || rowName == "到达城市"
        || rowName == "车次/航班"  {
        if  one_e.fInvoicetypeId.unwrap == InvoiceType.huoche_92 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.planeTax_90   {
            return true
         } else {
            return false
        }
    }
    if  rowName == "始发站" || rowName == "终点站" {
        if  one_e.fInvoicetypeId.unwrap == InvoiceType.qichepiao_93   {
            return true
         } else {
            return false
        }
    }
    if  rowName == "出口" || rowName == "入口" {
        if  one_e.fInvoicetypeId.unwrap == InvoiceType.highSpeedTax_20 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.tongxingTax_14   {
            return true
         } else {
            return false
        }
    }
    if  rowName == "校验码末6位" || rowName == "数电票号码末6位" {
        if  one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_normal_04 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_normal_dianzi_10 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.zzs_juan_11 ||
                one_e.fInvoicetypeId.unwrap == InvoiceType.shudianP_24 ||

                one_e.fInvoicetypeId.unwrap == InvoiceType.SZ_QKL_81  {
            return true
         } else {
            return false
        }
    }
    if rowName == "发票类型" || rowName ==  "报销类型" || rowName == "公司名称" ||
        rowName == "发票日期" || rowName ==  "发票金额" || rowName == "价税合计" ||
        rowName == "" || rowName ==  "" || rowName == "" {
        return true
    }
    return false
}


